var e = require("utils/function.js"),
    t = new(require("utils/qqmap-wx.js"))({
        key: "EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD"
    }),
    n = require("siteinfo.js").siteroot.replace("app/index.php", "api.php?s="),
    a = wx.createInnerAudioContext();

a.obeyMuteSwitch = !1;

var o, i, s = !1;

App({
    // 现在的城市
    gongture: '',
    travel_type: 2,
    onlineCallbacks: [],
    wsAddOnline: function (e) {
        this.onlineCallbacks.push(e), s && e(!0);
    },
    wsRemoveOnline: function (e) {
        var t = this.onlineCallbacks.indexOf(function (t) {
            return t === e;
        }); -
        1 !== t && this.onlineCallbacks.splice(t, 1);
    },
    callOnlinecallback: function (e) {
        this.onlineCallbacks.forEach(function (t) {
            t && t(e);
        });
    },
    test: 1,
    driver_position: [{
        latitude: "",
        longitude: ""
    }],
    actual_km: "",
    actual_km_price: "",
    timer: null,
    latitude: "",
    longitude: "",
    img: "/images/user/",
    city: "",
    api: require("api.js"),
    siteInfo: require("siteinfo.js"),
    user_location: {},
    webRoot: null,
    currentPage: null,
    is_binding: 0,
    shareInfo: {},
    wait_time: 0,
    get_order: 0,
    like: 1,
    driver_url: 0,
    postlist: [],
    longitudes: "",
    latitudes: "",
    navTo: function (e) {
        wx.navigateTo({
            url: e
        });
    },
    showToast: function (e, t, n, a) {
        wx.showToast({
            title: e,
            icon: 1 == t ? "success" : "none",
            mask: !0,
            duration: n || 1500,
            success: function () {
                setTimeout(function () {
                    a && a();
                }, n || 0);
            }
        });
    },
    reverseGeocoder: function (e) {
        t.reverseGeocoder({
            location: {
                latitude: e.lat,
                longitude: e.lng
            },
            get_poi: 1,
            success: function (t) {
                e.success(t);
            }
        });
    },
    setApi: function () {
        var e = this.siteInfo.siteroot;
        e = e.replace("app/index.php", ""), e += "api.php/?s=", this.api = function t(n) {
            for (var a in n) "string" == typeof n[a] ? n[a] = n[a].replace("{$_api_root}", e) : n[a] = t(n[a]);
            return n;
        }(this.api);
        var t = this.api.default.index,
            n = t.substr(0, t.indexOf("/api.php"));
        this.webRoot = n;
    },
    startReportHeart: function (e) {
        var t = this,
            n = {};
        n.type = "driver_position", n.order_no = e, t.timer = setInterval(function () {
            wx.getLocation({
                altitude: !0,
                type: "gcj02",
                isHighAccuracy: !0,
                highAccuracyExpireTime: "3500",
                success: function (e) {
                    t.longitudes = e.longitude, t.latitudes = e.latitude, n.lat = e.latitude, n.lng = e.longitude;
                    var a = wx.getStorageSync("temporary_position");
                    a && a.lat == n.lat || t.send(n), wx.setStorageSync("temporary_position", n);
                }
            });
        }, 5e3);
    },
    sendDriverPosition: function (e) {
        var t = this,
            n = {};
        n.type = "driver_position", n.order_no = e, wx.getLocation({
            altitude: !0,
            type: "gcj02",
            isHighAccuracy: !0,
            highAccuracyExpireTime: "3500",
            success: function (e) {
                t.longitudes = e.longitude, t.latitudes = e.latitude, n.lat = e.latitude, n.lng = e.longitude;
                var a = wx.getStorageSync("temporary_position");
                a && a.lat == n.lat || t.send(n), wx.setStorageSync("temporary_position", n);
            }
        });
    },
    uploadLocation: function (e) {
        var t = this,
            n = {};
        n.type = "driverToStart_position", n.order_no = e, t.timer = setInterval(function () {
            wx.getLocation({
                altitude: !0,
                type: "gcj02",
                success: function (e) {
                    n.lat = e.latitude, n.lng = e.longitude, t.send(n);
                }
            });
        }, 5e3);
    },
    cache: function () {
        switch (arguments.length) {
            case 1:
                var e = wx.getStorageSync((arguments.length <= 0 ? void 0 : arguments[0]) + "Until");
                return e ? (new Date().getTime() > e && (wx.removeStorageSync(arguments.length <= 0 ? void 0 : arguments[0]),
                        wx.removeStorageSync((arguments.length <= 0 ? void 0 : arguments[0]) + "Until")),
                    wx.getStorageSync(arguments.length <= 0 ? void 0 : arguments[0])) : wx.getStorageSync(arguments.length <= 0 ? void 0 : arguments[0]);

            case 2:
                return null === (arguments.length <= 1 ? void 0 : arguments[1]) ? wx.removeStorageSync(arguments.length <= 0 ? void 0 : arguments[0]) : wx.setStorageSync(arguments.length <= 0 ? void 0 : arguments[0], arguments.length <= 1 ? void 0 : arguments[1]);

            case 3:
                wx.setStorageSync(arguments.length <= 0 ? void 0 : arguments[0], arguments.length <= 1 ? void 0 : arguments[1]),
                    wx.setStorageSync((arguments.length <= 0 ? void 0 : arguments[0]) + "Until", new Date().getTime() + 1e3 * (arguments.length <= 2 ? void 0 : arguments[2]));
        }
    },
    uploadOrder: function (e) {
        var t = this,
            n = (this.timer, {});
        n.type = "getOrder_status", n.order_no = e, t.send(n);
    },
    endReportHeart: function () {
        clearInterval(this.timer);
    },
    waitTime: function () {
        var e = wx.getStorageSync("timeWait") || 0;
        o = setInterval(function () {
            wx.setStorageSync("timeWait", e++);
        }, 1e3);
    },
    endWaitTime: function () {
        clearInterval(o), wx.setStorageSync("timeWait", "");
    },
    onHide: function () {
        var e = this,
            t = 0;
        wx.startLocationUpdateBackground({
            success: function (n) {
                wx.onLocationChange(function (n) {
                    ++t % 5 == 0 && e.Request({
                        url: "driver/sleepUploadLocation",
                        method: "post",
                        data: {
                            lat: n.latitude,
                            lng: n.longitude
                        }
                    }).then(function (e) {
                        e.code;
                    });
                });
            },
            fail: function (e) {}
        });
    },
    musicPlay: function (e) {
        var t = wx.getBackgroundAudioManager();
        t.title = "订单提醒", t.src = e;
    },

    onLaunch: function () {
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res);
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        })

        var e = this;
        wx.setKeepScreenOn({
            keepScreenOn: !0
        }), this.setApi(), this.updateEdi(), this.getMapSetting(), wx.getSetting({
            success: function (t) {
                t.authSetting["scope.userInfo"] && wx.getUserProfile({
                    success: function (t) {
                        console.log(t);
                        e.globalData.userInfo = t.userInfo, e.userInfoReadyCallback && e.userInfoReadyCallback(t);
                    }
                }), t.authSetting["scope.userLocationBackground"];
            }
        }), this.getShare();
    },
    getMapSetting: function (e) {
        var t = this;
        t.request({
            url: t.api.default.map_key,
            method: "post",
            data: {},
            success: function (t) {
                wx.setStorageSync('servernum', t.data.phone)

                1 == t.code && (wx.setStorageSync("MAP_KEY", t.data.q_map_app_key), wx.setStorageSync("OPEN_LIMIT_DES", t.data.open_limit_des),
                    wx.setStorageSync("OPEN_UPLOAD_PIC", 1 == t.data.open_upload_pic), wx.setStorageSync("OPEN_CAR_INFO", 1 == t.data.open_car_info),
                    e && (e.data.showDriver = t.data.open_show_drivers));
            }
        });
    },
    updateEdi: function () {
        if (!wx.getUpdateManager) return wx.showModal({
            title: "提示",
            content: "您的微信版本过低,请进行升级",
            showCancel: !1
        }), !1;
        var e = wx.getUpdateManager();
        e.onCheckForUpdate(function (e) {}), e.onUpdateReady(function () {
            wx.showModal({
                title: "更新提示",
                content: "新版本已经准备好，是否重启应用？",
                success: function (t) {
                    t.confirm && e.applyUpdate();
                }
            });
        }), e.onUpdateFailed(function () {
            wx.showModal({
                title: "提示",
                content: "下载新版本失败，请删除小程序后重新进入",
                showCancel: "false"
            });
        });
    },
    getUserInfo: function (e) {
        var t = this;
        wx.getUserProfile({
            success: function (e) {
                wx.login({
                    success: function (n) {
                        console.log(n);
                        t.request({
                            url: t.api.user.login,
                            method: "post",
                            data: {
                                code: n.code,
                                iv: e.iv,
                                encryptedData: e.encryptedData
                            },
                            success: function (e) {
                                console.log(e);
                                1 == e.code && (this.is_binding = e.data.is_binding, wx.setStorageSync("access_token", e.data.access_token),
                                    wx.setStorageSync("serverphone", e.data.serverphone), 1 == e.data.type && 1 == e.data.audit && 1 == e.data.status && wx.reLaunch({
                                        url: "../../index/index"
                                    }), wx.setStorageSync("is_binding", e.data.is_binding));
                            }
                        });
                    }
                });
            }
        });
    },
    getlocation: function () {
        console.log('ninininini');
        var e = this;
        wx.getLocation({
            type: "gcj02",
            success: function (t) {
                var n = t.latitude,
                    a = t.longitude,
                    o = (t.speed, t.accuracy, t.latitude + "," + t.longitude);
                wx.request({
                    url: "https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1",
                    data: {
                        key: "YLFBZ-WHAWI-ZXUGH-53Q65-TOJ7E-ADBNQ",
                        location: o
                    },
                    method: "GET",
                    success: function (t) {
                        wx.setStorageSync("startAddress", {
                            title: t.data.result.address,
                            address: t.data.result.address,
                            location: {
                                lat: n,
                                lng: a
                            }
                        }), "" != wx.getStorageSync("userMessage") && e.request({
                            url: e.api.real_time.add,
                            method: "post",
                            data: {
                                lat: n,
                                lng: a
                            },
                            success: function (e) {
                                wx.setStorageSync("positioning", e.data);
                            }
                        });
                    },
                    fail: function () {
                        e.getlocation();
                    },
                    complete: function (e) {}
                });
            }
        });
    },
    getdlocation: function () {
        var e = this;
        "" != wx.getStorageSync("access_token") && 1 == wx.getStorageSync("usertype") && wx.getLocation({
            type: "gcj02",
            success: function (t) {
                var n = t.latitude,
                    a = t.longitude;
                e.posting(n, a);
            }
        });
    },
    routeLPlan: function (e, n) {
        var a = [];
        return t.direction({
            mode: "driving",
            from: e,
            to: n,
            success: function (e) {
                for (var t = e.result.routes[0].polyline, n = 2; n < t.length; n++) t[n] = Number(t[n - 2]) + Number(t[n]) / 1e6;
                for (n = 0; n < t.length; n += 2) a.push({
                    latitude: t[n],
                    longitude: t[n + 1]
                });
            },
            fail: function (e) {},
            complete: function (e) {}
        }), a;
    },
    Request: function (e) {
        var t = this;
        e.data ? e.data : e.data = {};
        var a = wx.getStorageSync("access_token");
        return e.data.access_token = a, e.data._uniacid = t.siteInfo.uniacid, e.data._acid = t.siteInfo.acid,
            new Promise(function (a, o) {
                wx.request({
                    url: n + e.url,
                    data: e.data,
                    method: e.method,
                    header: {},
                    success: function (e) {
                        -100 == e.data.code ? wx.showModal({
                            title: "提示",
                            content: "小程序应用未注册，请联系开发者",
                            showCancel: !1
                        }) : -1 == e.data.code && t.navTo("/pages/logs/logs"), a(e.data);
                    },
                    error: function (e) {
                        o(e);
                    }
                });
            });
    },
    request: function (e) {
        e.data || (e.data = {});
        var t = wx.getStorageSync("access_token");
        t && (e.data.access_token = t), e.data._uniacid = this.siteInfo.uniacid, e.data._acid = this.siteInfo.acid,
            wx.request({
                url: e.url,
                header: e.header || {
                    "content-type": "application/x-www-form-urlencoded"
                },
                data: e.data || {},
                method: e.method || "GET",
                dataType: e.dataType || "json",
                success: function (t) {
                    -100 == t.data.code ? wx.showModal({
                        title: "提示",
                        content: "小程序应用未注册，请联系开发者",
                        showCancel: !1
                    }) : -1 == t.data.cod ? that.navTo("/pages/logs/logs") : e.success && e.success(t.data);
                },
                fail: function (t) {
                    var n = getApp();
                    n.is_on_launch ? (n.is_on_launch = !1, wx.showModal({
                        title: "",
                        content: t.errMsg,
                        showCancel: !1,
                        success: function (t) {
                            t.confirm && e.fail && e.fail(t);
                        }
                    })) : e.fail && e.fail(t);
                },
                complete: function (t) {
                    200 != t.statusCode && (console.log("--- request http error >>>"), console.log(t.statusCode),
                        console.log(t.data), console.log("<<< request http error ---")), e.complete && e.complete(t);
                }
            });
    },
    globalData: {
        userInfo: null
    },
    getShare: function () {
        var e = this;
        this.request({
            url: this.api.share.index,
            method: "post",
            data: {},
            success: function (t) {
                console.log(t);
                1 == t.code ? (wx.setNavigationBarTitle({
                    title: t.data.title
                }), e.shareInfo = t.data, wx.setStorageSync("mp3", t.data.videomp3)) : wx.showToast({
                    title: t.msg
                });
            }
        });
    },
    shareCouponsMessage: function (e) {
        this.request({
            url: this.api.share.coupons,
            method: "post",
            data: {
                uid: e
            },
            success: function (e) {
                e.code;
            }
        });
    },
    shareAppMessage: function (e) {
        return {
            title: this.shareInfo.title,
            imageUrl: this.shareInfo.image,
            desc: this.shareInfo.desc,
            path: "/pages/map/driverServer/driverServer?uid=" + wx.getStorageSync("uid")
        };
    },
    posting: function (e, t) {
        var n = this,
            a = wx.getStorageSync("access_token"),
            o = {};
        o.type = "positioning", o.room_id = n.siteInfo.acid, o.imei = "", o.origin = 0,
            o.lat = e, o.lng = t, o.token = a, n.send(o);
    },
    send: function (e) {
        i.send({
            data: JSON.stringify(e)
        });
       
    },
    onlineCallback: function (e) {
        e.setData({
            online: s
        });
    },
    gateway: function (e, t, n) {
        var a = {};
        a.type = "say", a.order_no = e, a.status = t, a.deletesay = n, this.send(a);
    },
    driver: function (e) {
        var t = this,
            n = {};
        n.type = "driver", n.client_name = wx.getStorageSync("access_token"), n.room_id = t.siteInfo.acid,
            n.order_no = e, t.send(n);
    },
    onShow: function (e) {
        this.forever_realtive(), wx.stopLocationUpdate({
            success: function (e) {}
        });
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        })

    },
    forever_realtive: function () {
        var t = this;
        if (!s) {
            var n = this.siteInfo.siteroot;
            n = (n = n.replace("/app/index.php", "")).replace("https", "wss"), (i = wx.connectSocket({
                url: n
            })).onError(function (e) {
                s ? i.close() : setTimeout(function () {
                    t.forever_realtive();
                }, 5e3);
            }), i.onOpen(function (e) {
                s = !0, t.callOnlinecallback(!0);
                var n = {};
                n.type = "login", n.client_name = wx.getStorageSync("access_token"), n.room_id = t.siteInfo.acid,
                    n.uid = wx.getStorageSync("access_token"), t.send(n);
            }), i.onClose(function (e) {
                s = !1, t.callOnlinecallback(!1), setTimeout(function () {
                    t.forever_realtive();
                });
            }), i.onMessage(function (n) {
                var a = JSON.parse(n.data);
                console.log(a);
                switch (a.type) {
                    case "ping":
                        var o = {};
                        o.type = "pong", t.send(o);
                        break;

                    case "login":
                        "" != a.client_name && a.client_name == wx.getStorageSync("access_token") && (0 == a.is_online && 1 == a.origin && 2 == a.is_app_order ? wx.showModal({
                            title: "提示",
                            content: "当前司机已在APP端登录,小程序将不再上报位置"
                        }) : wx.getStorageSync("access_token") && setInterval(function () {
                            t.getdlocation();
                        }, 1e4));
                        break;

                    case "driver_position":
                        var i = JSON.parse(a.data.position_point),
                            s = JSON.parse(a.data.target_adds_location);
                        t.actual_km = a.data.actual_km, t.actual_km_price = a.data.actual_km_price, t.driver_position = t.routeLPlan(i[i.length - 1], {
                            latitude: s.lat,
                            longitude: s.lng
                        });
                        break;

                    case "driver":
                        var that = this
                        1 == a.status && 1 == wx.getStorageSync("usertype") && setTimeout(() => {

                            wx.getLocation({
                                type: "gcj02",
                                success: function (o) {
                                    wx.request({
                                        url: 'https://dishichuxing.cn/api.php/?s=order/getOrder',
                                        method: "POST",
                                        data: {
                                            accuracy: o.accuracy,
                                            like: 0,
                                            latitude: o.latitude,
                                            longitude: o.longitude,
                                            speed: o.speed,
                                            access_token: wx.getStorageSync('access_token'),
                                            _uniacid: 1,
                                            _acid: 1,
                                        },
                                        success: function (res) {

                                            var p = 'https://dishichuxing.cn'
                                            getApp().musicPlay(p + res.data.data[0].voice_announcements)

                                        }
                                    })
                                }
                            })

                        }, 2000)


                        break;

                    case "driver_task":
                        t.uploadLocation(a.order_no), t.musicPlay(wx.getStorageSync("newmp")), e.intoPageHandler("/pages/driverOrder/orderedStatus/orderedStatus?orderstart=1&order_no=" + a.order_no);
                        break;

                    case "say":
                        1 == a.status ? wx.redirectTo({
                            url: "/pages/map/getOrderNotGoing/getOrderNotGoing?order_no=" + a.order_no
                        }) : 2 == a.status ? wx.redirectTo({
                            url: "/pages/map/orderGoing/orderGoing?order_no=" + a.order_no
                        }) : 3 == a.status ? wx.redirectTo({
                            url: "/pages/pay/paidOrder/paidOrder?order_no=" + a.order_no
                        }) : 4 == a.status ? wx.redirectTo({
                            url: "/pages/userOrder/orderDetail/orderDetail?order_no=" + a.order_no
                        }) : 5 == a.status ? setTimeout(function () {
                            wx.reLaunch({
                                url: "/pages/map/driverServer/driverServer?deleteOrder=true"
                            });
                        }, 1500) : 8 == a.status ? (wx.showToast({
                            title: "用户已取消订单"
                        }), setTimeout(function () {
                            wx.reLaunch({
                                url: "/pages/index/index"
                            });
                        }, 1500)) : 9 == a.status ? (wx.showToast({
                            title: "系统取消订单"
                        }), setTimeout(function () {
                            wx.reLaunch({
                                url: "/pages/index/index"
                            });
                        }, 1500)) : 10 == a.status && t.musicPlay("https://driving.4hl.cn/WeChat/resource/video/pay_end.mp3");
                        break;

                    case "positioning":
                        break;

                    case "driverToStart_position":
                        wx.setStorageSync("driver_now_position", a), 4 == a.data.is_service && t.endReportHeart();
                }
            });
        }
    },
    PushfromId: function (e) {
        console.log('19');
        var t = e;
        // t && this.request({
        //     url: this.api.share.getformid,
        //     method: "post",
        //     data: {
        //         formid: t
        //     },
        //     success: function(e) {
        //         e.code;
        //         console.log(e.type);

        //         // this.setData({
        //         //     gongtrue:e.
        //         // })
        //     }
        // });
    }
});